import Session from "../model/session";
import userJwtService from "@/server/service/user-jwt-service";
import cookieService from "./cookie-service";
import { CookieNames } from "@/shared/cookies";
import { ReadonlyRequestCookies } from "next/dist/server/web/spec-extension/adapters/request-cookies";

async function getSessionFromJwtToken(jwt: string | null | undefined): Promise<Session> {
  if (!jwt) {
    return new Session({ base: { authed: false } });
  }

  const result = await userJwtService.verifyJwt(jwt);
  if (!result.ok) {
    return new Session({ base: { authed: false } });
  }

  return new Session({ base: { authed: true, userId: result.userId, sessionId: result.sessionId } });
}

export async function getSessionFromHeaders(headers: Headers): Promise<Session> {
  const cookies = cookieService.getCookies(headers);
  const jwt = cookies[CookieNames.TOKEN];
  return await getSessionFromJwtToken(jwt);
}

export async function getSessionFromRequest(req: Request): Promise<Session> {
  return await getSessionFromHeaders(req.headers);
}

export async function getSessionFromNextCookies(nextCookies: ReadonlyRequestCookies): Promise<Session> {
  const jwt = nextCookies.get(CookieNames.TOKEN)?.value;
  return await getSessionFromJwtToken(jwt);
}
